package com.demo.mongo.service.impl;

import com.demo.mongo.entity.Test;
import com.demo.mongo.service.TestService;
import lombok.AllArgsConstructor;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.util.List;

/**
 * 测试使用 mongo 服务
 *
 * @author YT
 * @date 2019-08-19
 */
@Service
@AllArgsConstructor
public class TestServiceImpl implements TestService {

    private final MongoTemplate mongoTemplate;


    @Override
    public void insert(Test test) {
        mongoTemplate.insert(test);
    }

    @Override
    public void batchInsert(List<Test> tests) {
        mongoTemplate.insert(tests, Test.class);
    }

    @Override
    public Test findById(String id) {
        return mongoTemplate.findById(id, Test.class);
    }

    @Override
    public List<Test> findToSendList(Data startTime, Data endTime) {
        Query query = new Query(Criteria.where("create_time").gte(startTime).lt(endTime));
        List<Test> tests = mongoTemplate.find(query, Test.class);
        return tests;
    }

    @Override
    public void update(Test test) {
        Query query = new Query(Criteria.where("_id").is(test.getId()));
        Update update = new Update()
                .set("name", test.getName())
                .set("age", test.getAge())
                .set("address", test.getAddress());
        // 更新查询返回结果集的第一条
        mongoTemplate.updateFirst(query, update, Test.class);
    }

    @Override
    public void delete(String id) {
        Query query = new Query(Criteria.where("_id").is(id));
        mongoTemplate.remove(query, Test.class);
    }

    @Override
    public void save(Test test) {
        mongoTemplate.save(test);
    }

    @Override
    public List<Test> findList() {
        return mongoTemplate.findAll(Test.class);
    }
}
